function ALI = gs_ReadBGImage(IMS,ALA,Alpha)
%gs_ReadBGImage
%
%       ALI = gs_ReadBGImage(IMS,ALA,Alpha)
%
% This functions reads a brackground image related to the struct variable 
% IMS (see below) and superimposes is to a figure with axis scaling ALA. 
% Valid input arguments:
%   - IMS is a struct variable whose fields are Image (value: filename
%     of background image) and Vertices (value: MATLAB file carrying a
%     a variable ALI with the coordinates of the vartices of the area
%     represented by the image, in the form [Xdatamin, Xdatamax, Ydatamin, 
%     Ydatamax]);
%   - IMS is undefined or empty. In this case no a reference image is
%     used and ALI = [];
%   - ALA is the scaling of the figure to which the background image 
%     should be superimposed, in the form ALA = [XMIN XMAX YMIN YMAX];
%   - ALA is undefined or empty. In this case, the coordinates in 
%     IMS.Vertices are used;
%   - Alpha is a number in the range 0-1 (extremes not included). In this
%     case, the transparency is Alpha;
%   - Alpha is undefined, empty or outside the valid range. In this case, 
%     the default value Alpha = 0.3 is used.
%
% The output variable ALI is [Xdatamin, Xdatamax, Ydatamin, Ydatamax].

% G. Teza, 2022.

if (nargin < 3) || isempty(Alpha) || (Alpha <= 0) || (Alpha >= 1)
    Alpha = 0.3;
end
if nargin < 2 
    ALA = [];
end
if nargin < 1 || isempty(IMS)
    ALI = [];
    return
end

RefImFile = IMS.Image;
RefLimFile = IMS.Vertices;

Am = imread(RefImFile); 

if ~ishold
    hold on;
end

ALIs = load(RefLimFile);
ALI = ALIs.ALI;
Xv = ALI(1:2); Yv = ALI(3:4);

Im = image(flipud(Am),'Xdata',Xv,'Ydata',Yv); 
Im.AlphaData = Alpha;

if ~isempty(ALA) 
    axis(ALA);
end